package com.hut.oa.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.mail.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hut.oa.model.bean.AddressBook;
import com.hut.oa.model.bean.AddressDir;
import com.hut.oa.model.bean.Attachment;
import com.hut.oa.model.bean.EmailManage;
import com.hut.oa.model.bean.Status;
import com.hut.oa.model.bean.User;
import com.hut.oa.model.dao.AttachmentDao;
import com.hut.oa.model.dao.address.AddressDao;
import com.hut.oa.model.dao.address.AddressDirDao;
import com.hut.oa.model.dao.mail.MailDao;
import com.hut.oa.model.dao.system.StatusDao;
import com.hut.oa.model.dao.user.UserDao;
import com.hut.oa.model.mapper.AddressBookMapper;
import com.hut.oa.service.AddressService;
import com.hut.oa.service.AttachmentService;
import com.hut.oa.service.EmailService;
import com.hut.oa.service.FileService;
import com.hut.oa.service.SystemService;

@Controller
@RequestMapping("/address")
public class AddressController {
	
	@Autowired
	private AddressDirDao adddirdao;
	
	@Autowired
	private UserDao udao;
	
	@Autowired
	private AddressDao adddao;
	
	@Autowired
	private FileService fileser;
	
	@Autowired
	private AddressBookMapper addmapper;
	
	@Autowired
	private AddressService addressser;
	@RequestMapping
	public String toMail(HttpSession session, Model model,@RequestParam(value="value",required=false)String value,@PageableDefault(value = 8, sort = {"id"}) Pageable pageable) throws ParseException {
		User u=(User)session.getAttribute("userinfo");
		model.addAttribute("dirlist", adddirdao.findByUser(u));
		model.addAttribute("href","/address");
		model.addAttribute("statusid", 0);
		model.addAttribute("typeid", 0);
		/*
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
         //过去七天
        c.setTime(new Date());
        c.add(Calendar.DATE, - 7);
        Date d = c.getTime();
        String day = format.format(d);
        startnew Date().setDate(new Date().getDate()+1));
      */
        Date end=new Date();
        end.setDate(end.getDate()-7);
        Date start=new Date();
        
        if(null!=value){
			model.addAttribute("addresslist",adddao.findbyUsernameOrtel(pageable,u,value));
		}else{
			/*model.addAttribute("addresslist",adddao.findByUser(pageable, u));*/
			model.addAttribute("addresslist",adddao.selectbytime(pageable,end,start,u));
		}
		return "address/address";
	}
	
	@RequestMapping(value="/addAddress")
	public String addAddress(HttpSession session, Model model,@PageableDefault(value =6, sort = {"id"}) Pageable pageable) {
		User u=(User)session.getAttribute("userinfo");
		model.addAttribute("userlist", udao.findByIdNot(pageable,u.getId()));
		model.addAttribute("dirlist", adddirdao.findByUser(u));
		return "address/addAddress";
	}
	
	@RequestMapping(value="/viewAddress")
	public String viewAddress(HttpSession session, Model model,@RequestParam("addressid")Long addressid) {
		User u=(User)session.getAttribute("userinfo");
		model.addAttribute("userlist", udao.findByIdNot(u.getId()));
		model.addAttribute("dirlist", adddirdao.findByUser(u));
		model.addAttribute("address",adddao.findById(addressid));
		return "address/viewAddress";
	}
	@RequestMapping(value="/viewuser")
	public String viewuser(HttpSession session, Model model,@RequestParam("addressid")Long addressid) {
		User u=(User)session.getAttribute("userinfo");
		model.addAttribute("dirlist", adddirdao.findByUser(u));
		model.addAttribute("user", udao.findById(addressid));
		return "address/viewAddress";
	}
	
	//新建分类
	@RequestMapping(value="/newtype")
	public @ResponseBody List<AddressDir> newtype(HttpSession session,@RequestParam("value")String value){
		User u=(User)session.getAttribute("userinfo");
		AddressDir dir=new AddressDir(value,u);
		adddirdao.save(dir);
		List<AddressDir> list=adddirdao.findByUser(u);
		return list;	
	}
	//保存新建联系人
	@RequestMapping(value="/keepaddress",method=RequestMethod.POST)
	
	public void saveaddress(HttpServletRequest request,HttpSession session,@RequestParam(value="file",required=false)MultipartFile file,AddressBook address) throws IllegalStateException, IOException{
		User u=(User)session.getAttribute("userinfo");
		address.setUser(u);
		address.setCreatetime(new Date());
		if(file.getSize()>0){
			String path= fileser.uploadefile(file,"address\\"+u.getId()+"");
			address.setPhoto(path);
		}
		String shareuser=request.getParameter("shareuser").trim();
		List<User> list=new ArrayList<>();
		if(null!=shareuser&&!shareuser.equals("")){
			String user[]=shareuser.split("、");
			if(user.length>0){
				for (String uid : user) {
					User use=udao.findById(Long.parseLong(uid));
					list.add(use);
				}
			}
			address.setAddressuser(list);
		}
		adddao.save(address);
	}
	//不同分类中的联系人
		@RequestMapping(value="/addresstypedata")
		public String addresstypedata(HttpSession session,Model model,@PageableDefault(value = 8, sort = {"id"}) Pageable pageable,@RequestParam("typeid")Long typeid,@RequestParam(value="statusid",required=false)Long statusid){
			User u=(User)session.getAttribute("userinfo");
			AddressDir dir=new AddressDir();
			dir.setId(typeid);
			model.addAttribute("dirlist", adddirdao.findByUser(u));
			
			model.addAttribute("typeid", typeid);
			if(null!=statusid){
				model.addAttribute("statusid", statusid);
				model.addAttribute("addresslist",adddao.findByUserAndTypeAndDir(pageable, u,statusid,dir));
				model.addAttribute("href","/address/addresstypedata?statusid="+statusid+"&&typeid="+typeid+"");
			}else{
				model.addAttribute("statusid", 0);
				model.addAttribute("addresslist",adddao.findByUserAndDir(pageable, u,dir));
				model.addAttribute("href","/address/addresstypedata?statusid=&&typeid="+typeid+"");
			}
			return "address/address";
		}
	//不同类型的通讯录
		@RequestMapping(value="/addressstatus")
		public String addressstatus(HttpSession session,Model model,@PageableDefault(value = 8, sort = {"id"}) Pageable pageable,@RequestParam("statusid")Long statusid ,@RequestParam(value="typeid",required=false)Long typeid){
			User u=(User)session.getAttribute("userinfo");
			model.addAttribute("dirlist", adddirdao.findByUser(u));
			model.addAttribute("statusid",statusid);
			AddressDir dir=new AddressDir();
			dir.setId(typeid);
			if(statusid!=3&&statusid!=4){
				if(null!=typeid){
					model.addAttribute("typeid", typeid);
					model.addAttribute("addresslist",adddao.findByUserAndTypeAndDir(pageable,u,statusid,dir));
					model.addAttribute("href","/address/addressstatus?statusid="+statusid+"&&typeid="+typeid+"");
				}else{
					model.addAttribute("typeid",0);
					model.addAttribute("addresslist",adddao.findByUserAndType(pageable,u,statusid));
					model.addAttribute("href","/address/addressstatus?statusid="+statusid+"&&typeid=");
				}
			}else if(statusid==4){
				List<Map<String, Object>> list=addmapper.selectaddressbyid(u.getId());
				List<Long> longlist=new ArrayList<>();
				for (Map<String, Object> map : list) {
					longlist.add(Long.parseLong(map.get("au_address_id")+""));
				}
				model.addAttribute("typeid",0);
				if(longlist.size()>0){
					model.addAttribute("shareaddresslist",adddao.findbyids(pageable,longlist));
				}
				model.addAttribute("href","/address/addresstypedata?statusid="+statusid+"&&typeid=");
			}else{
				model.addAttribute("typeid",0);
				model.addAttribute("userlist", udao.findByIdNot(pageable,u.getId()));
				model.addAttribute("href","/address/addresstypedata?statusid="+statusid+"&&typeid=");
			}
			return "address/address";
		}
		
	//编辑联系人
		@RequestMapping(value="/editaddress")
		public String editaddress(HttpSession session,Model model,@PageableDefault(value = 6, sort = {"id"}) Pageable pageable,@RequestParam("addressid")Long addressid){
			User u=(User)session.getAttribute("userinfo");
			model.addAttribute("userlist", udao.findByIdNot(u.getId()));
			model.addAttribute("dirlist", adddirdao.findByUser(u));
			model.addAttribute("address", adddao.findOne(addressid));
			model.addAttribute("userlist", udao.findByIdNot(pageable,u.getId()));
			List<Map<String, Object>> list=addmapper.selectaddressbyaddid(addressid);
			StringBuffer username = new StringBuffer();
			StringBuffer userid=new StringBuffer();
			for (Map<String, Object> map : list) {
				System.out.println(map+"ssssss");
				userid.append(map.get("au_user_id")+"、");
				username.append(udao.findOne(Long.parseLong(map.get("au_user_id")+"")).getRealName()+"、");
			}
			if(username.length()>1){
				model.addAttribute("username", username.substring(0, username.length()-1).toString());
				model.addAttribute("userid", userid.substring(0, userid.length()-1).toString());
			}else{
				model.addAttribute("username","");
				model.addAttribute("userid","");
			}
			
			return "address/addAddress";
		}	
	//删除联系人
		@RequestMapping(value="/deleteaddress")
		public void deleteaddress(@RequestParam("value")Long value){
			addmapper.deletebyaddressid(value);
			adddao.delete(value);
		}
		//多个删除
		@RequestMapping(value="/deletemanyaddress")
		public void deleteaddress(@RequestParam(value="addressid",required=false)Long[] value){
			if(value.length>0){
				for (Long long1 : value) {
					addmapper.deletebyaddressid(long1);
					adddao.delete(long1);
				}
			}
		}
		//修改类型名字
		@RequestMapping(value="/updatetypename")
		public void updatetypename(HttpSession session,@RequestParam(value="value")String value,@RequestParam(value="dirid")Long dirid){
			User u=(User)session.getAttribute("userinfo");
			addressser.update(value, dirid, u);
		}
		@RequestMapping(value="/deleteajax")
		public @ResponseBody List<AddressDir> deleteajax(HttpSession session,@RequestParam("dirid")Long dirid){
			User u=(User)session.getAttribute("userinfo");
			adddirdao.delete(dirid);
			AddressDir dir=new AddressDir();
			dir.setId(dirid);
			List<AddressBook> addresslist=adddao.findByUserAndDir(u,dir);
			
			if(addresslist.size()>0){
				for (AddressBook addressBook : addresslist) {
					adddao.delete(addressBook);
				}
			}
			List<AddressDir> list=adddirdao.findByUser(u);
			return list;
		}
		//删除被分享的
		@RequestMapping(value="/deleteshareuser")
		@ResponseBody
		public void deleteshareuser(HttpSession session,@RequestParam("value")Long value){
			User u=(User)session.getAttribute("userinfo");
			addmapper.deletebyaddressidanduser(value, u.getId());
		}
		//删除共享的
		@RequestMapping(value="/deletegonxiang")
		public void deletegonxiang(HttpSession session,@RequestParam("value")Long value){
			User u=(User)session.getAttribute("userinfo");
			addmapper.deletebyaddressid(value);
			adddao.delete(value);
		}	
		
}
